import Layout from '@/layout'
import { log } from 'util'
/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj

}

export function parseMenuData(data) {
  const map = {};
  const topLevelCategories = ['home', 'setting']; // 假设有一级菜单为'main'和'setting'

  // 初始化map
  data.firstList.concat(data.secondList, data.thirdList).forEach(item => {
    if (!map[item.id]) {
      map[item.id] = { ...item, children: [] };
    }
  });

  // 构建父子关系并按顶级类别分类
  let categorizedMenus = topLevelCategories.reduce((acc, category) => {
    acc[category] = [];
    return acc;
  }, {});

  Object.values(map).forEach(item => {
    if (item.parent_id === 0) { // 处理一级菜单
      const firstLevelItem = item;

      // 找到该一级菜单下的所有二级菜单
      const secondLevelItems = Object.values(map).filter(secondLevelItem => secondLevelItem.parent_id === firstLevelItem.id);
      secondLevelItems.forEach((secondLevelItem, index, array) => {
        // 找到该二级菜单下的所有三级菜单
        secondLevelItem.children = Object.values(map).filter(thirdLevelItem => thirdLevelItem.parent_id === secondLevelItem.id);
        secondLevelItem.path = '/' + secondLevelItem.resource_name
        array[index] = secondLevelItem;
      });
      categorizedMenus[firstLevelItem.resource_name] = secondLevelItems;
    }
  });

  // 清理无用属性，并生成最终的路由配置
  function cleanMenuItem(item) {
    delete item.parent_id;
    delete item.resource_url;
    delete item.icon_url;
    if (item.children.length === 0) {
      delete item.children;
    } else {
      item.children = item.children.map(cleanMenuItem);
    }
    return item;
  }

  // 对每个一级菜单下的二级菜单进行清理
  Object.keys(categorizedMenus).forEach(category => {
    categorizedMenus[category] = categorizedMenus[category].map(cleanMenuItem);
  });


  return categorizedMenus; // 返回按类别分类的路由列表
}

/**
 * 列表型数据转化树形
 */
export function transListToTreeData(list, rootValue) {
  const arr = []
  list.forEach(item => {
    if (item.parent_id === rootValue) {
      // 找到了匹配的节点
      arr.push(item)
      // 当前节点的id 和 当前节点的子节点的pid是想等的
      const children = transListToTreeData(list, item.id) // 找到的节点的子节点
      if (children.length) {
        item.children = children // 将子节点赋值给当前节点
      }

    }
  })
  return arr
}

/**
 * 列表型数据转化树形 -章节
 */
export function transListToTreeDataOnChapter(list, rootValue, level = 0) {
  const arr = []
  list.forEach(item => {
    if (item.parent_id === rootValue) {
      const node = {
        ...item,
        label: item.name, // 将 name 赋值给 label
        level: level,     // 添加层级字段
        editing: false,   // 默认不处于编辑模式
      };

      // 递归查找子节点，并提升 level 层级
      const children = transListToTreeDataOnChapter(list, item.id, level + 1);
      if (children.length) {
        node.children = children;
      }

      arr.push(node);

    }
  })
  return arr
}

/**
 * 将嵌套章节数据扁平化并添加层级信息
 * @param {Array} items 嵌套数组（如 this.chapters）
 * @param {number} level 当前层级（递归使用）
 * @returns {Array} 扁平化后的数组，每个元素包含 level 属性
 */
export function flattenChapters(items, level = 0) {
  const result = [];

  function flatten(items, level) {
    for (const item of items) {
      const newItem = { ...item, level };
      result.push(newItem);
      if (item.children && item.children.length > 0) {
        flatten(item.children, level + 1);
      }
    }
  }

  flatten(items, level);
  return result;
}




